import { ServerResponse, createServer } from "http";
import { EventEmitter } from "events";
import { Application } from "express";
import { createDecipheriv, createHash } from "crypto";
import { MongoDBInst } from './lib/TeMongodb';
import { LogMgr } from "./lib/LogMgr";
import { levelDBInst } from "./lib/TeLeveldb";


class WebMgr extends EventEmitter {
    private _app: Application;

    ready = false;
    init(port: number) {
        var express = require("express");
        this._app = express();
        createServer(<any>this._app).listen(port);
        var bodyParser = require('body-parser');
        this._app.use(bodyParser.urlencoded({ extended: true }));
        this._app.use(bodyParser.json());

        this._app.all('/dbtest', this._ondbtest.bind(this));

        this._app.all('/memory', this._onMemory.bind(this));
        this._app.get('/logs', this._onlogs.bind(this));
        this._app.get('/logs/get', this._onlogsget.bind(this));
        this._app.get('/erros', this._onerrors.bind(this));
        this._app.get('/erros/get', this._onerrorsget.bind(this));

        this.ready = true;
    }

    private _ondbtest(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        var kk = "t" + Date.now();
        levelDBInst.put(kk, Math.random().toString(), () => {
            levelDBInst.get(kk, (v) => {
                res.writeHead(200, 'ok');
                res.write(v);
                res.end();
            })
        })
    }

    private _onMemory(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        res.writeHead(200, 'ok');
        res.write(JSON.stringify(process.memoryUsage()));
        res.end();

    }

    private _onlogs(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        // 返回所有logs的名目
        let out = [];
        let log_keys = LogMgr.lastOutCache.keys;
        for (let i = 0; i < log_keys.length; i++) {
            out.push(`<a href="${req.url}/get?key=${log_keys[i]}">${log_keys[i]}</a>`);
        }

        let str = '<head><meta charset="utf-8"></head><body>' + out.join('<br>') + '</body>';
        res.writeHead(200, 'ok');
        res.write(str);
        res.end();
    }

    private _onlogsget(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        // 返回所有logs的名目
        let loginfo = LogMgr.lastOutCache.get(param.key) || '';
        let str = '<head><meta charset="utf-8"></head><body>' + loginfo + '</body>';
        res.writeHead(200, 'ok');
        res.write(str);
        res.end();
    }

    private _onerrors(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        // 返回所有logs的名目
        let out = [];
        let log_keys = LogMgr.lastErrorCache.keys;
        for (let i = 0; i < log_keys.length; i++) {
            out.push(`<a href="${req.url}/get?key=${log_keys[i]}">${log_keys[i]}</a>`);
        }

        let str = '<head><meta charset="utf-8"></head><body>' + out.join('<br>') + '</body>';
        res.writeHead(200, 'ok');
        res.write(str);
        res.end();
    }

    private _onerrorsget(req: Request, res: ServerResponse) {
        var param: any;
        if (req.method == 'GET') {
            param = req['query'];
        }
        else if (req.method == 'POST') {
            param = req['body'];
        }
        else {
            res.writeHead(404, 'method error');
            res.end();
            return;
        }

        // 返回所有logs的名目
        let loginfo = LogMgr.lastErrorCache.get(param.key) || '';
        let str = '<head><meta charset="utf-8"></head><body>' + loginfo + '</body>';
        res.writeHead(200, 'ok');
        res.write(str);
        res.end();
    }
}

export var webInst = new WebMgr();
